package org.tamal.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class UtilServlet.
 */
@WebServlet(description = "Utility Servlet", urlPatterns = { "/UtilServlet" })
public final class UtilServlet extends HttpServlet {

    private static final long serialVersionUID = -2176772736496974284L;
    private static final int NO_CONTENT = 204;

    /**
     * Called by the server (via the service method) to allow a servlet to
     * handle a GET request.
     *
     * @param request
     *            request parameter
     * @param response
     *            response parameter
     * @throws ServletException
     *             exception
     * @throws IOException
     *             exception
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String query = request.getParameter("q");
        try (PrintWriter out = response.getWriter()) {
            if (query == null) {
                response.setContentType("text/html");
                out.println("<html><body><h1>Available queries</h1><ul>");
                out.println("<li><a href='?q=time'>Time</a></li>");
                out.println("</ul></body></html>");
                return;
            }
        }
        if ("time".equals(query)) {
            response.setContentType("text/plain");
            response.getWriter().println(new java.util.Date());
        } else {
            response.sendError(NO_CONTENT, "invalid query");
        }
    }
}
